package com.front.web.lvyou_specialty_front;

import com.bootdo.common.utils.CurrencyUtils;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.lvyou_specialty.domain.LvyouSpecialtyOrderContent;
import com.bootdo.lvyou_specialty.service.LvyouSpecialtyMerchantService;
import com.bootdo.lvyou_specialty.service.LvyouSpecialtyOrderContentService;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;
import com.front.web.lvyou_specialty_front.pagevo.MerchantVo;
import org.apache.regexp.REUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/f/merchantController")
public class MerchantFrontController {

    @Autowired
    private UserService userService;

    @Autowired
    private LvyouSpecialtyMerchantService lvyouSpecialtyMerchantService;

    @Autowired
    private LvyouSpecialtyOrderContentService lvyouSpecialtyOrderContentService;

    /**
     * 这里的uid指的是用户的商家id
     * http://lvyou.lxjhua.work/f/merchantController/getUserInfo
     * @param uid
     * @return
     */
    @RequestMapping("getUserInfo")
    public R login(@RequestParam(value = "uid")Long uid) {
        UserDO userDO = userService.getByMerchantId(uid);
        UserDO user = new UserDO();
        user.setUserId(userDO.getUserId());
        user.setMerchantId(userDO.getMerchantId());
        user.setUsername(userDO.getUsername());
        return R.ok().put("i", user).put("token", MD5Utils.encrypt(user.getUsername() + user.getUserId(), "lvyou_merchant"));
    }


    /**
     * http://lvyou.lxjhua.work/f/merchantController/getMerchantOrder
     * @param merchantId
     * @param token
     * @return
     */
    @RequestMapping("getMerchantOrder")
    public R getMerchantOrder(@RequestParam("uid")Long merchantId,
                              @RequestParam("token")String token,
                              @RequestParam(value = "status", defaultValue = "0")Integer status,
                              @RequestParam(value = "pageNo", defaultValue = "1")Integer pageNo,
                              @RequestParam(value = "pageSize", defaultValue = "15")Integer pageSize) {

        UserDO user = userService.getByMerchantId(merchantId);
        if (user == null) {
            return R.error();
        }

        if (!StringUtils.equals(MD5Utils.encrypt(user.getUsername() + user.getUserId(), "lvyou_merchant"), token)){
            return R.error();
        }
        Map<String, Object> param = new HashMap<>();
        param.put("merchantId", merchantId);
        param.put("offset", (pageNo - 1) * pageSize);
        param.put("limit", pageSize);
        param.put("merchantFlag", 1);
        if (status != 0) {
            param.put("status", status);
        } else {
            param.put("statusFlag", 1);
        }
        Map<String, MerchantVo> merchantVoMap = new HashMap<>();
        List<String> listMerchantOrder = lvyouSpecialtyOrderContentService.listGroup(param);
        List<LvyouSpecialtyOrderContent> list = lvyouSpecialtyOrderContentService.listGroupList(listMerchantOrder);

        param.remove("offset");
        param.remove("limit");
        param.remove("status");
        param.put("statusFlag", 1);

        int total = 0;
        List<Integer> totalList = lvyouSpecialtyOrderContentService.merchantCount(param);
//        for (Integer one: totalList) {
//            total += one;
//        }

        param.remove("statusFlag");

        param.put("status", 2);
        List<LvyouSpecialtyOrderContent> dealList = lvyouSpecialtyOrderContentService.list(param);
        Integer dealNumber = dealList.size();
        for (LvyouSpecialtyOrderContent one: list) {
            if (merchantVoMap.containsKey(one.getMerchantOrderNo())) {

                MerchantVo merchantVo = merchantVoMap.get(one.getMerchantOrderNo());
                merchantVo.setNumber(merchantVo.getNumber() + 1);
                merchantVo.getGoodsImages().add(one.getGoodsImages());
                merchantVo.setTotalFee(CurrencyUtils.add(new BigDecimal(merchantVo.getTotalFee()), new BigDecimal(one.getRealFee())).doubleValue());

            } else {
                MerchantVo merchantVo = new MerchantVo();
                merchantVo.setMerchantOrder(one.getMerchantOrderNo());
                merchantVo.setStatus(one.getStatus());
                merchantVo.setContentId(one.getId());
                List<String> imageList = new ArrayList<>();
                imageList.add(one.getGoodsImages());
                merchantVo.setGoodsImages(imageList);
                merchantVo.setTotalFee(one.getRealFee());
                merchantVo.setNumber(1);

                merchantVoMap.put(one.getMerchantOrderNo(), merchantVo);
            }
        }

        List<MerchantVo> resultList = new ArrayList<>();
        for (Map.Entry one: merchantVoMap.entrySet()) {
            resultList.add((MerchantVo) one.getValue());
        }

        resultList.sort(new Comparator<MerchantVo>() {
            @Override
            public int compare(MerchantVo o1, MerchantVo o2) {
                Long minus = o2.getContentId() - o1.getContentId();
                return minus.intValue();
            }
        });

        return R.ok().put("l", resultList).put("total", totalList.size()).put("dealNumber", dealNumber);
    }

    /**
     * http://lvyou.lxjhua.work/f/merchantController/getOneMerchantOrder
     * @param merchantId
     * @param token
     * @param merchantOrder
     * @return
     */
    @RequestMapping("getOneMerchantOrder")
    public R getOneMerchantOrder(@RequestParam("uid")Long merchantId,
                              @RequestParam("token")String token,
                                 @RequestParam("merchantOrder")String merchantOrder) {

        UserDO user = userService.getByMerchantId(merchantId);
        if (user == null) {
            return R.error();
        }

        if (!StringUtils.equals(MD5Utils.encrypt(user.getUsername() + user.getUserId(), "lvyou_merchant"), token)){
            return R.error();
        }

        List<LvyouSpecialtyOrderContent> orderList = lvyouSpecialtyOrderContentService.getByMerchantOrderNo(merchantOrder);
        double freight = 0D;
        double totalFee = 0D;
        String orderNo = "";
        String merchantOrderNo = "";
        for (LvyouSpecialtyOrderContent one: orderList) {
            orderNo = one.getGoodsOrderNo();
            merchantOrderNo = one.getMerchantOrderNo();
            freight = CurrencyUtils.add(new BigDecimal(one.getFreight()), new BigDecimal(freight)).doubleValue();
            totalFee = CurrencyUtils.add(new BigDecimal(one.getRealFee()), new BigDecimal(totalFee)).doubleValue();
        }
        return R.ok().put("l", orderList).put("freight", freight).put("totalFee", totalFee).put("orderNo", orderNo)
                .put("merchantOrderNo", merchantOrder);
    }

    /**
     * http://lvyou.lxjhua.work/f/merchantController/subDelivery
     * @param merchantId
     * @param token
     * @param merchantOrder
     * @param logisticsType
     * @param logisticsNumber
     * @return
     */
    @RequestMapping("subDelivery")
    public R subDelivery(@RequestParam("uid")Long merchantId,
                         @RequestParam("token")String token,
                         @RequestParam("merchantOrder")String merchantOrder,
                         @RequestParam(value = "logisticsType", defaultValue = "")String logisticsType,
                         @RequestParam(value = "logisticsNumber", defaultValue = "")String logisticsNumber) {

        UserDO user = userService.getByMerchantId(merchantId);
        if (user == null) {
            return R.error();
        }

        if (!StringUtils.equals(MD5Utils.encrypt(user.getUsername() + user.getUserId(), "lvyou_merchant"), token)){
            return R.error();
        }

        if (StringUtils.isEmpty(logisticsNumber) || StringUtils.isEmpty(logisticsType) ||  StringUtils.isEmpty(merchantOrder) ) {
            return R.error("参数错误");
        }

        if (lvyouSpecialtyOrderContentService.editDelivery(merchantOrder, logisticsType, logisticsNumber) == 0) {
            return R.error();
        }

        return R.ok("发货成功");
    }

}
